package com.mijie.homi.search.service;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.mijie.homi.common.constant.MCKey;

import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.GetFuture;

@Service
public class MemcacheService {

	private MemcachedClient client;
	
	private Logger logger = Logger.getLogger(MemcacheService.class);
	
	public MemcacheService(){
		try {
			client =new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public long incr(String key,int by){
		long v = 0;
		if(client!=null) v = client.incr(MCKey.KEY_PREFIX+key, by, 1);
		return v;
	}
	
	public long decr(String key,int by){
		long v = 0;
		if(client!=null) v = client.decr(MCKey.KEY_PREFIX+key, by);
		return v;
	}
	
	public void set(String prefix,String key,int exp,Object o){
		if(client!=null){
			client.set(MCKey.KEY_PREFIX+prefix+key, exp, o);
		}
	}
	
	
	public Object get(String prefix,String key){
		Object value = null;
		GetFuture<Object> f = null;
		if(client!=null){
			f = client.asyncGet(MCKey.KEY_PREFIX+prefix+key);
			try {
				value = f.get(5, TimeUnit.SECONDS);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			} 
		}
		return value;
	}
	
	public String getString(String prefix,String key){
		String value = null;
		GetFuture<Object> f = null;
		if(client!=null){
			try{
				f =  client.asyncGet(MCKey.KEY_PREFIX+prefix+key);
			value = (String) f.get(5,TimeUnit.SECONDS);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			} 
		}
		return value;
	}
	
	public void delete(String prefix,String key){
		if(client!=null){
			client.delete(MCKey.KEY_PREFIX+prefix+key);
		}
	}
}
